package com.intelli4.pos.ui;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class NumberPadPanel extends JPanel implements ActionListener {
	private static final long serialVersionUID = 4487652006461713353L;

	private List<NumberPadListener> listeners = new ArrayList<NumberPadListener>();
	private JButton[] btns = new JButton[10];
	private JButton delBtn = new JButton("<");
	private JButton dotBtn = new JButton(".");

	public NumberPadPanel() {
		init();
	}

	protected void init() {
		setLayout(new GridLayout(4, 3, 5, 5));

		addComponentListener(new ComponentAdapter() {
			@Override
			public void componentResized(ComponentEvent e) {
				int s = getHeight() / 7;

				Font font = new Font(delBtn.getFont().getName(), Font.BOLD, s);
				delBtn.setFont(font);
				
				dotBtn.setFont(font);

				for (int i = 0; i < 10; i++)
					btns[i].setFont(font);
			}
		});

		for (int i = 0; i < 10; i++) {
			JButton btn = new JButton();
			btn.addActionListener(this);

			btns[i] = btn;
			add(btn);
		}

		btns[0].setText("7");
		btns[1].setText("8");
		btns[2].setText("9");
		btns[3].setText("4");
		btns[4].setText("5");
		btns[5].setText("6");
		btns[6].setText("1");
		btns[7].setText("2");
		btns[8].setText("3");
		btns[9].setText("0");

		dotBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				for (NumberPadListener listener : listeners) {
					listener.onDecimalPoint();
				}
			}
		});
		add(dotBtn);

		delBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				for (NumberPadListener listener : listeners) {
					listener.onDelete();
				}
			}
		});
		add(delBtn);
	}

	public void addNumberPadListener(NumberPadListener listener) {
		listeners.add(listener);
	}

	public void removeNumberPadListener(NumberPadListener listener) {
		listeners.remove(listener);
	}

	public static void main(String[] args) {
		JFrame frame = new JFrame(NumberPadPanel.class.getName());
		NumberPadPanel panel = new NumberPadPanel();
		frame.add(panel, BorderLayout.CENTER);
		frame.setSize(400, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		for (NumberPadListener listener : listeners) {
			listener.onNumber(Integer.parseInt(e.getActionCommand()));
		}
	}
}
